// import { TIMEOUT, STATUS_OK, baseURL, statusCodeMsg } from './config';
import axios from 'axios';
// import router from '../router';
import { dialog } from "@/common/dialog";
// import { redirectToLogin } from "@/common/common";
// import { useRouter } from 'vue-router'
// const router = useRouter()

import router from '@/router'

const STATUS_OK = 200;

const TIMEOUT = 30000;

const baseURL = {
  // dev: '',
  // prod: 'admin/'
};

// Vue.prototype.$baseURL = baseURL;

const statusCodeMsg = [{
  code: 401,
  msg: 'Unauthorized'
},
  {
    code: 403,
    msg: 'forbidden'
  }
];


// Axios configuration
export const baseUrl = baseURL.dev;
const xhr = axios.create({
  baseURL: '',
  // baseURL: baseURL.dev,
  timeout: TIMEOUT,
  headers: {
    'Type': 'AppWeb',
    // 'Content-Type': 'Content-Type: application/json;charset=utf-8'
  }
});

// Add request interceptor
xhr.interceptors.request.use(
    function (config) {
      
      // Add tokens
      // let token = sessionStorage.getItem('token');
      // if (token) {
      //   config.headers.common['token'] = token;
      // }
      // If the request is a post request, use QS to configure the request parameters
      if (config.method === 'post') {
        return config;
      }
      // Add a random parameter to the parameters of the get request
      if (config.method === 'get') {
        const random = Math.random();
        if (config.params) {
          config.params.r = random;
        } else {
          config.params = {
            r: random
          };
        }
      }
      return config;
    },
    function (error) {
      // Do something when the request is incorrect
      return Promise.reject(error);
    }
);




// export function redirectToLogin() {
//   console.log('Login timeout')
  
// }

// Add response interceptor
xhr.interceptors.response.use(
    function (response) {
      // console.log('response----------',response)z
      const statusCode = response.status;
      if (response.status === STATUS_OK) {
        if (response.data.timeOut) {
          dialog.info('登录超时 ，2秒后将会跳转到登录页面');
          setTimeout(() => {
            sessionStorage.clear()
            router.replace('/login')
          }, 2000);
        } else {
          
          return response.data;
        }
      } else {
        // Interface exception return
        statusCodeMsg.forEach(function (item, index) {
          if (statusCode === item.code) {
            return Promise.reject(response.data);
          }
        });
      }
    },
    function (error) {
      return Promise.reject(error);
    }
);

export default xhr;
